package com.example.x3day04.util;

import com.example.x3day04.net.ApiService;
import com.google.gson.Gson;

import java.io.IOException;
import java.nio.file.Path;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpUtile {
    private static volatile HttpUtile httpUtile;
    private Retrofit.Builder builder;
    private ApiService apiService = null;
    private HttpUtile(){
        //初始化ok
        OkHttpClient okHttpClient = initOkhttp();
        //初始化Retrofter
        initRetrofit(okHttpClient);
    }

    public static HttpUtile getInstance(){
        if (httpUtile == null){
            synchronized (HttpUtile.class){
                if (httpUtile == null){
                    httpUtile = new HttpUtile();
                }
            }
        }
        return httpUtile;
    }
    private void initRetrofit(OkHttpClient okHttpClient) {
        builder = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create());

    }

    private OkHttpClient initOkhttp() {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new LogInterceptor())
                .build();
        return client;
    }

    private class LogInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            String string = response.peekBody(2048).string();
            LogUtil.print(string);
            return response;
        }
    }
    public ApiService getApiService(){
        if (apiService == null){
            synchronized (HttpUtile.class){
                if (apiService == null){
                    apiService = builder.baseUrl(ApiService.FULIURL)
                            .build()
                            .create(ApiService.class);
                }
            }
        }
        return apiService;
    }
}



























